package com.ruoyi.ldzlsb.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.ldzlsb.domain.SbMaintenancePlan;
import com.ruoyi.ldzlsb.domain.SbMaintenanceRecord;
import com.ruoyi.ldzlsb.service.ISbMaintenancePlanService;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 保养计划Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/sb/maintenance/plan")
public class SbMaintenancePlanController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(SbMaintenancePlanController.class);
    
    @Autowired
    private ISbMaintenancePlanService sbMaintenancePlanService;
    


    /**
     * 查询保养计划列表
     */
    //@RequiresPermissions("sb:plan:list")
    @GetMapping("/list")
    public TableDataInfo list(SbMaintenancePlan sbMaintenancePlan)
    {
        startPage();
        List<SbMaintenancePlan> list = sbMaintenancePlanService.selectSbMaintenancePlanList(sbMaintenancePlan);
        return getDataTable(list);
    }

    /**
     * 导出保养计划列表
     */
    //@RequiresPermissions("sb:plan:export")
    @Log(title = "保养计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SbMaintenancePlan sbMaintenancePlan)
    {
        List<SbMaintenancePlan> list = sbMaintenancePlanService.selectSbMaintenancePlanList(sbMaintenancePlan);
        ExcelUtil<SbMaintenancePlan> util = new ExcelUtil<SbMaintenancePlan>(SbMaintenancePlan.class);
        util.exportExcel(response, list, "保养计划数据");
    }

    /**
     * 获取保养计划详细信息
     */
    //@RequiresPermissions("sb:plan:query")
    @GetMapping(value = "/{planId}")
    public AjaxResult getInfo(@PathVariable("planId") Long planId)
    {
        SbMaintenancePlan plan = sbMaintenancePlanService.selectSbMaintenancePlanByPlanId(planId);
        
        // 获取周期配置信息
        if (plan != null) {
            // TODO: 从周期配置表中获取配置信息
            logger.info("获取计划周期配置信息: {}", planId);
        }
        
        return AjaxResult.success(plan);
    }

    /**
     * 新增保养计划
     */
    //@RequiresPermissions("sb:plan:add")
    @Log(title = "保养计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbMaintenancePlan sbMaintenancePlan)
    {
        // 处理周期配置信息
        if (StringUtils.isNotBlank(sbMaintenancePlan.getCycleConfigJson())) {
            // 这里可以保存周期配置到专门的表中
            logger.info("保存周期配置: {}", sbMaintenancePlan.getCycleConfigJson());
        }
        
        if (!sbMaintenancePlanService.checkPlanCodeUnique(sbMaintenancePlan)) {
            return AjaxResult.error("新增保养计划'" + sbMaintenancePlan.getPlanCode() + "'失败，计划编号已存在");
        }
        
        sbMaintenancePlan.setCreateBy(SecurityUtils.getUsername());
        return toAjax(sbMaintenancePlanService.insertSbMaintenancePlan(sbMaintenancePlan));
    }

    /**
     * 修改保养计划
     */
    //@RequiresPermissions("sb:plan:edit")
    @Log(title = "保养计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbMaintenancePlan sbMaintenancePlan)
    {
        // 处理周期配置信息
        if (StringUtils.isNotBlank(sbMaintenancePlan.getCycleConfigJson())) {
            // 这里可以更新周期配置到专门的表中
            logger.info("更新周期配置: {}", sbMaintenancePlan.getCycleConfigJson());
        }
        
        if (!sbMaintenancePlanService.checkPlanCodeUnique(sbMaintenancePlan)) {
            return AjaxResult.error("修改保养计划'" + sbMaintenancePlan.getPlanCode() + "'失败，计划编号已存在");
        }
        
        sbMaintenancePlan.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sbMaintenancePlanService.updateSbMaintenancePlan(sbMaintenancePlan));
    }

    /**
     * 删除保养计划
     */
    //@RequiresPermissions("sb:plan:remove")
    @Log(title = "保养计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{planIds}")
    public AjaxResult remove(@PathVariable Long[] planIds)
    {
        return toAjax(sbMaintenancePlanService.deleteSbMaintenancePlanByPlanIds(planIds));
    }

    /**
     * 生成保养记录
     */
    //@RequiresPermissions("sb:plan:generate")
    @Log(title = "生成保养记录", businessType = BusinessType.INSERT)
    @PostMapping("/generate/{planId}")
    public AjaxResult generateRecord(@PathVariable("planId") Long planId)
    {
        try {
            SbMaintenancePlan plan = sbMaintenancePlanService.selectSbMaintenancePlanByPlanId(planId);
            if (plan == null) {
                return AjaxResult.error("保养计划不存在");
            }
            
            if (!"1".equals(plan.getPlanStatus())) {
                return AjaxResult.error("保养计划未启用，无法生成保养记录");
            }
            
            SbMaintenanceRecord record = sbMaintenancePlanService.createMaintenanceRecordFromPlan(plan);
            
            // 这里需要调用保养记录服务来保存记录
            // sbMaintenanceRecordService.insertSbMaintenanceRecord(record);
            
            return AjaxResult.success("保养记录生成成功", record);
        } catch (Exception e) {
            logger.error("生成保养记录失败", e);
            return AjaxResult.error("生成保养记录失败：" + e.getMessage());
        }
    }

    /**
     * 生成保养计划编号
     */
    @GetMapping("/generate/code")
    public AjaxResult generatePlanCode()
    {
        String planCode = sbMaintenancePlanService.generatePlanCode();
        return AjaxResult.success(planCode);
    }

    /**
     * 检查计划编号唯一性
     */
    @GetMapping("/check/{planCode}")
    public AjaxResult checkPlanCodeUnique(@PathVariable("planCode") String planCode)
    {
        SbMaintenancePlan plan = new SbMaintenancePlan();
        plan.setPlanCode(planCode);
        boolean isUnique = sbMaintenancePlanService.checkPlanCodeUnique(plan);
        return AjaxResult.success(isUnique);
    }

    /**
     * 修改保养计划状态
     */
    //@RequiresPermissions("sb:plan:edit")
    @Log(title = "保养计划状态", businessType = BusinessType.UPDATE)
    @PutMapping("/status/{planId}/{status}")
    public AjaxResult updateStatus(@PathVariable("planId") Long planId, @PathVariable("status") String status)
    {
        SbMaintenancePlan plan = new SbMaintenancePlan();
        plan.setPlanId(planId);
        plan.setPlanStatus(status);
        plan.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sbMaintenancePlanService.updateSbMaintenancePlan(plan));
    }
} 